package com.company.project.controller.ldjsc.meeting;

import com.company.project.common.utils.DataResult;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.vosk.Model;
import org.vosk.Recognizer;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/sxzy/voice")
@Api(tags = "视频会议-音频转文字")
public class SpeechToTextController {


    @ApiOperation(value = "音频转文字")
    @PostMapping("/text")
    @ResponseBody
    public DataResult speechToText() throws IOException {
        // 1. 加载模型
        Model model = new Model("/data/vosk-model-cn-0.22/vosk-model-cn-0.22");
        // 2. 创建识别器（设置关键词）
        JsonParser parser = new JsonParser();
        Recognizer recognizer = new Recognizer(model, 16000);
        recognizer.setWords(true); // 启用时间戳
        // 3. 音频输入处理
        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("/data/ldjsc/output412414.wav"))) {
            AudioFormat format = audioInputStream.getFormat();
            byte[] buffer = new byte[4096];

            StringBuilder test = new StringBuilder();
            while (true) {
                int bytesRead = audioInputStream.read(buffer, 0, buffer.length);
                if (bytesRead == -1) break;  // 文件读取完毕

                if (recognizer.acceptWaveForm(buffer, bytesRead)) {
                    String json = recognizer.getResult();
                    JsonObject result = parser.parse(json).getAsJsonObject();
                    test.append(result.get("text").getAsString());
                    //加换行符
                    test.append("\n");
                }
            }
            return DataResult.success(test.toString());
        } catch (UnsupportedAudioFileException e) {
            return DataResult.fail("音频文件格式不支持");
        }
    }
}
